/**
 * 用户相关服务
 */

const util = require('util.js');
const api = require('../config/api.js');

/**
 * 调用微信登录
 */
function loginByWeixin() {
  let code = null;
  return new Promise(function (resolve, reject) {
    return util.login().then((res) => {
      code = res.code;
      
      //登录远程服务器

      util.request(api.AuthLoginByWeixin, { wx_code: code}, 'POST').then(res => {
        if (res.code === 200) {
          //存储用户信息
          wx.setStorageSync('userInfo', res.data.userInfo);
          wx.setStorageSync('token', res.data.token); 
        }
        resolve(res);
      }).catch((err) => {
        reject(err);
      });
    }).catch((err) => {
      reject(err);
    })
  });
}

/**
 * 获取wx session
 */
function code2Session() {
  let code = null;
  return new Promise(function (resolve, reject) {
    return util.login().then((res) => {
      code = res.code;
      wx.setStorageSync('code', code);
      //登录远程服务器
      util.request(api.AuthCode2Session, { wx_code: code }, 'POST').then(res => {
        // let unionid = res.data.unionid;
        // wx.setStorageSync('unionid', unionid);
        resolve(res);
      }).catch((err) => {
        reject(err);
      });
    }).catch((err) => {
      reject(err);
    })
  });
}

//手机号验证
function checkMobile(mobile) {
  return new Promise(function (resolve, reject) {
    let myreg = /^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\d{8}$/;
    resolve(myreg.test(mobile));
  });
}

module.exports = {
  loginByWeixin,
  checkMobile,
  code2Session
};











